package com.ruoyi.service.controller;

import java.math.BigDecimal;
import java.util.*;

import com.ruoyi.basics.domain.Point;
import com.ruoyi.basics.domain.User;
import com.ruoyi.basics.service.IPointService;
import com.ruoyi.basics.service.IUserService;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.service.domain.Reality;
import com.ruoyi.service.domain.Trade;
import com.ruoyi.service.service.IRealityService;
import com.ruoyi.service.service.ITradeService;
import com.ruoyi.service.utils.ServiceUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.service.domain.Basics;
import com.ruoyi.service.service.IBasicsService;
import com.ruoyi.framework.web.base.BaseController;
import com.ruoyi.common.page.TableDataInfo;
import com.ruoyi.common.base.AjaxResult;
import com.ruoyi.common.utils.ExcelUtil;

/**
 * 电量电费录入数据基础 信息操作处理
 *
 * @author wangbing
 * @date 2019-01-02
 */
@Controller
@RequestMapping("/service/basics")
public class BasicsController extends BaseController {
    private String prefix = "service/basics";

    @Autowired
    private IBasicsService basicsService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IPointService pointService;
    @Autowired
    private ITradeService tradeService;
    @Autowired
    private IRealityService realityService;
    @Autowired
    private ServiceUtils utils;

    private static HashMap<Long, Integer> idMap = new HashMap<>();

    @RequiresPermissions("service:basics:view")
    @GetMapping()
    public String basics(ModelMap mmap) {
//        List<User> users = userService.selectUserList(null);
        List<User> users = userService.selectUserListByData(new User());
        mmap.put("users", users);
        return prefix + "/basics";
    }

    /**
     * 查询电量电费录入数据基础列表
     */
    @RequiresPermissions("service:basics:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Basics basics) {
        System.out.print(basics.toString());
        startPage();
//        List<Basics> list = basicsService.selectBasicsList(basics);
        List<Basics> list = basicsService.selectBasicsListByData(basics);
        for (Basics b : list) {
            Reality reality = new Reality();
            reality.setBasicsId(b.getId());
            List<Reality> realities = realityService.selectRealityList(reality);
            for (Reality r : realities) {
                reality.setEleAccount(reality.getEleAccount() == null ?
                        r.getEleAccount() : (reality.getEleAccount().add(r.getEleAccount())));
                reality.setDHPrice(reality.getDHPrice() == null
                        ? r.getDHPrice() : (reality.getDHPrice().add(r.getDHPrice())));
                reality.setDHAcount(reality.getDHAcount() == null
                        ? r.getDHAcount() : (reality.getDHAcount().add(r.getDHAcount())));
            }
            System.out.println(reality);
            b.setEleAccount(reality.getEleAccount().stripTrailingZeros().toPlainString());
            b.setdHPrice(reality.getDHPrice().stripTrailingZeros().toPlainString());
            b.setdHAccount(reality.getDHAcount().stripTrailingZeros().toPlainString());
        }
        return getDataTable(list);
    }


    /**
     * 导出电量电费录入数据基础列表
     */
    @RequiresPermissions("service:basics:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Basics basics) {
        List<Basics> list = basicsService.selectBasicsList(basics);
        ExcelUtil<Basics> util = new ExcelUtil<Basics>(Basics.class);
        return util.exportExcel(list, "basics");
    }

    /**
     * 导出电量电费录入数据基础列表
     */
    @RequiresPermissions("service:basics:export")
    @PostMapping("/exportSelect")
    @ResponseBody
    public AjaxResult exportSelect(String ids) {
        List<Basics> basics = basicsService.selectBasicsByIds(ids);
        return utils.export(basics, "basics");
    }

    /**
     * 新增电量电费录入数据基础
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
//        List<User> users = userService.selectUserList(null);
        List<User> users = userService.selectUserListByData(new User());
        mmap.put("users", users);
        return prefix + "/add";
    }

    /**
     * 新增保存电量电费录入数据基础
     */
    @RequiresPermissions("service:basics:add")
    @Log(title = "电量电费录入数据基础", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Basics basics) {
        basics.setOperationUserId(getUserId());
        basics.setOperationDate(new Date());
        int id = basicsService.insertBasics(basics);
        Point point = new Point();
        point.setUserId(Long.parseLong(basics.getUserId().toString()));
        idMap.put(getUserId(), basics.getId());//记录添加的ID
        List<Point> points = pointService.selectPointList(point);
        if (CollectionUtils.isEmpty(points)) {
            throw new BusinessException("未配置计量点，请先配置计量点或联系管理员！");
        }
        utils.setBasics(basics);
        for (Point p : points) {
            utils.insertDataByPoint(p);
        }
        if (id == 0) {
            AjaxResult.error();
        }
        return AjaxResult.success(basics.getId() + "");
    }

    /**
     * 修改电量电费录入数据基础
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Integer id, ModelMap mmap) {
        Basics basics = basicsService.selectBasicsById(id);
        mmap.put("basics", basics);
        List<User> users = userService.selectUserList(null);
        mmap.put("users", users);
        return prefix + "/edit";
    }

    /**
     * 详细列表
     */
    @RequiresPermissions("basics:user:list")
    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") Integer userId, ModelMap mmap) {
        idMap.put(getUserId(), userId);//缓存用户录入的ID
        stepToDetail(userId, mmap);
        return prefix + "/detail";
    }

    /**
     * 给跳转设置默认值
     *
     * @param userId
     * @param mmap
     */
    private void stepToDetail(@PathVariable("id") Integer userId, ModelMap mmap) {
        Basics basics = basicsService.selectBasicsById(userId);
        User user = userService.selectUserById(Long.valueOf(basics.getUserId()));
        Trade trade = new Trade();
        trade.setBasicsId(basics.getId());
        List<Trade> trades = tradeService.selectTradeList(trade);
        if (CollectionUtils.isEmpty(trades)) {
            throw new BusinessException("未配置计量点，请先配置计量点或联系管理员！");
        }
        List<String> pointIds = new ArrayList<>();
        for (Trade t : trades) {
            pointIds.add(t.getPointId() + "");
        }
        List<Point> points = pointService.selectPointByIds(pointIds);
        mmap.put("basics", basics);
        mmap.put("user", user);
        mmap.put("points", points);
        utils.setModelMap(mmap, points.get(0).getId(), basics.getId());
    }

    @GetMapping("/luru")
    public String luru(ModelMap mmap) {
        Integer userId = idMap.get(getUserId());
        if (userId == null) {
            throw new BusinessException("您未有录入项，请先新建或点击费用列表录入！");
        }
        stepToDetail(userId, mmap);
        return prefix + "/detail";
    }

    @PostMapping("/getPointInfo")
    @ResponseBody
    public AjaxResult getPointInfo(@RequestParam Map<String, Object> params) {
        Integer pointId = Integer.valueOf(params.get("pointId").toString());
        Integer basicsId = Integer.valueOf(params.get("basicsId").toString());
        return utils.getInfo(pointId, basicsId);
    }

    /**
     * 修改保存电量电费录入数据基础
     */
    @RequiresPermissions("service:basics:edit")
    @Log(title = "电量电费录入数据基础", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Basics basics) {
        return toAjax(basicsService.updateBasics(basics));
    }

    /**
     * 删除电量电费录入数据基础
     */
    @RequiresPermissions("service:basics:remove")
    @Log(title = "电量电费录入数据基础", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(basicsService.deleteBasicsByIds(ids));
    }

}
